import { create } from 'zustand';
import { Repository, RepositoryFile, Commit } from '@/types';
import { repoApi } from '@/services/api';

interface RepoState {
  repositories: Repository[];
  currentRepo: Repository | null;
  currentPath: string;
  currentBranch: string;
  currentFile: RepositoryFile | null;
  fileContent: string;
  files: RepositoryFile[];
  commits: Commit[];
  branches: string[];
  isLoading: boolean;
  error: string | null;
  
  fetchRepositories: () => Promise<void>;
  fetchRepository: (owner: string, repo: string) => Promise<void>;
  fetchContents: (owner: string, repo: string, path?: string, branch?: string) => Promise<void>;
  fetchFile: (owner: string, repo: string, path: string, branch?: string) => Promise<void>;
  fetchCommits: (owner: string, repo: string, branch?: string) => Promise<void>;
  fetchBranches: (owner: string, repo: string) => Promise<void>;
  saveFile: (owner: string, repo: string, path: string, content: string, message: string, branch?: string) => Promise<void>;
  setCurrentPath: (path: string) => void;
  setCurrentBranch: (branch: string) => void;
}

export const useRepoStore = create<RepoState>((set, get) => ({
  repositories: [],
  currentRepo: null,
  currentPath: '',
  currentBranch: 'master', // 默认分支
  currentFile: null,
  fileContent: '',
  files: [],
  commits: [],
  branches: [],
  isLoading: false,
  error: null,

  fetchRepositories: async () => {
    set({ isLoading: true, error: null });
    try {
      const repositories = await repoApi.getUserRepositories();
      set({ repositories });
    } catch (error: any) {
      set({ error: error.message || '获取仓库列表失败' });
    } finally {
      set({ isLoading: false });
    }
  },

  fetchRepository: async (owner: string, repo: string) => {
    set({ isLoading: true, error: null });
    try {
      const repository = await repoApi.getRepository(owner, repo);
      set({ currentRepo: repository });
      // 获取默认分支
      await get().fetchBranches(owner, repo);
    } catch (error: any) {
      set({ error: error.message || '获取仓库详情失败' });
    } finally {
      set({ isLoading: false });
    }
  },

  fetchContents: async (owner: string, repo: string, path: string = '', branch?: string) => {
    set({ isLoading: true, error: null });
    try {
      const branchToUse = branch || get().currentBranch;
      const files = await repoApi.getRepositoryContents(owner, repo, path, branchToUse);
      set({ files, currentPath: path });
    } catch (error: any) {
      set({ error: error.message || '获取仓库内容失败' });
    } finally {
      set({ isLoading: false });
    }
  },

  fetchFile: async (owner: string, repo: string, path: string, branch?: string) => {
    set({ isLoading: true, error: null });
    try {
      const branchToUse = branch || get().currentBranch;
      const file = await repoApi.getRepositoryFile(owner, repo, path, branchToUse);
      // 如果文件内容是Base64编码的，需要解码
      let content = '';
      if (file.content && file.encoding === 'base64') {
        content = atob(file.content.replace(/\n/g, ''));
      } else if (file.content) {
        content = file.content;
      }
      set({ currentFile: file, fileContent: content });
    } catch (error: any) {
      set({ error: error.message || '获取文件内容失败' });
    } finally {
      set({ isLoading: false });
    }
  },

  fetchCommits: async (owner: string, repo: string, branch?: string) => {
    set({ isLoading: true, error: null });
    try {
      const branchToUse = branch || get().currentBranch;
      const commits = await repoApi.getRepositoryCommits(owner, repo, branchToUse);
      set({ commits });
    } catch (error: any) {
      set({ error: error.message || '获取提交历史失败' });
    } finally {
      set({ isLoading: false });
    }
  },

  fetchBranches: async (owner: string, repo: string) => {
    set({ isLoading: true, error: null });
    try {
      const branches = await repoApi.getRepositoryBranches(owner, repo);
      set({ branches });
      // 如果有分支且当前没有设置分支，设置第一个分支为当前分支
      if (branches.length > 0 && !get().currentBranch) {
        set({ currentBranch: branches[0] });
      }
    } catch (error: any) {
      set({ error: error.message || '获取分支列表失败' });
    } finally {
      set({ isLoading: false });
    }
  },

  saveFile: async (owner: string, repo: string, path: string, content: string, message: string, branch?: string) => {
    set({ isLoading: true, error: null });
    try {
      const branchToUse = branch || get().currentBranch;
      await repoApi.createCommit(owner, repo, path, content, message, branchToUse);
      // 更新文件内容
      await get().fetchFile(owner, repo, path, branchToUse);
      // 更新提交历史
      await get().fetchCommits(owner, repo, branchToUse);
    } catch (error: any) {
      set({ error: error.message || '保存文件失败' });
    } finally {
      set({ isLoading: false });
    }
  },

  setCurrentPath: (path: string) => {
    set({ currentPath: path });
  },

  setCurrentBranch: (branch: string) => {
    set({ currentBranch: branch });
  },
}));